import axios from 'axios'
import { Toast } from 'vant'
import { getToken, removeToken } from '@/utils/storage'
import router from '@/router'
const http = axios.create({
  baseURL: 'http://interview-api-t.itheima.net/h5',
  timeout: 3000
})
// 添加请求拦截器
http.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  config.headers.Authorization = `Bearer ${getToken()}`
  return config
}, function (error) {
  Toast.success(error.response.data.message)
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
http.interceptors.response.use(function (response) {
  return response.data
}, function (error) {
  if (error.response.status === 401) {
    removeToken()
    router.push('/login')
  }
  if (error.response && error.response.data) {
    Toast.fail(error.response.data.message)
  }
  return Promise.reject(error)
})
export default http
